﻿using System;
using System.Linq;

namespace CML.Intercamber.Business.Dao
{
    public class ForgottenPasswordsDao
    {
        public static ForgottenPasswords Add(string email)
        {
            ForgottenPasswords res;
            using (var context = new IntercamberEntities())
            {
                var user = context.Users.FirstOrDefault(x => x.Email == email && x.Enabled);
                if (user == null)
                    return null;
                res = new ForgottenPasswords
                {
                    IdUser = user.IdUser, 
                    RequestDate = DateTime.Now, 
                    RequestKey = Guid.NewGuid(), 
                    ProcessDate = null, 
                    RequestProcessed = false
                };
                context.ForgottenPasswords.Add(res);
                context.SaveChanges();
            }
            return res;
        }

        public static ForgottenPasswords Find(Guid key)
        {
            ForgottenPasswords res;
            using (var context = new IntercamberEntities())
            {
                DateTime yesterday = DateTime.Now.AddDays(-1);
                res = context.ForgottenPasswords.FirstOrDefault(x => x.RequestKey == key && x.RequestDate > yesterday && x.ProcessDate == null);
            }
            return res;
        }

        public static bool UseKeyAndChangePassword(Guid key, string email, string newPassword)
        {
            using (var context = new IntercamberEntities())
            {
                DateTime yesterday = DateTime.Now.AddDays(-1);
                ForgottenPasswords res = context.ForgottenPasswords.FirstOrDefault(x => x.RequestKey == key && x.RequestDate > yesterday && x.ProcessDate != null);
                if (res == null)
                    return false;
                Users user = context.Users.FirstOrDefault(x => x.IdUser == res.IdUser);
                if (user == null || user.Email.ToLower().Trim() != email.ToLower().Trim())
                    return false;
                user.Password = newPassword;
                res.RequestProcessed = true;
                res.ProcessDate = DateTime.Now;
                context.SaveChanges();
            }
            return true;
        }
    }
}
